package com.choosefine.base.shixiaobao.common.utils;

import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.choosefine.base.shixiaobao.base.dto.DateDTO;
import com.choosefine.base.shixiaobao.common.def.ResultCode;
import com.choosefine.base.shixiaobao.common.exception.BusinessException;



public class DateUtils {
    
	/**
	 * 12.16 dzq 将时间字符串转化为dto
	 * @param data
	 * @return
	 * @throws ParseException 
	 */
	public static DateDTO conversionDateDto(String data,String fomart) throws ParseException{
		SimpleDateFormat sf=new SimpleDateFormat(fomart);
		DateDTO date=new DateDTO(); 
		Calendar c1=Calendar.getInstance();
		if(org.springframework.util.StringUtils.isEmpty(data)){//当时间未输入，则为所有
			date.setStartTime(0);
			date.setEndTime(System.currentTimeMillis());
			return date;
		}
		c1.setTime(sf.parse(data));
		date.setStartTime(c1.getTimeInMillis());//2016-10-01
		c1.add(Calendar.MONTH, 1);
		c1.add(Calendar.DAY_OF_MONTH, -1); //尽量传递准确的日期时间 add code by liaozhanggen 2017-01-03 15:30
		c1.set(Calendar.HOUR, 23);
		c1.set(Calendar.MINUTE, 59);
		c1.set(Calendar.SECOND, 59);
		date.setEndTime(c1.getTimeInMillis()); //2016-11-01
		return date;
	}
	
//	public static void main(String[] args) {
//		try {
//			conversionDateDto("2016年03月","yyyy年MM月");
//		} catch (ParseException e) {
//			e.printStackTrace();
//		}
//	}
	
	/**
	 * 12.9dzq 时间戳转化为 年-月-日 时：分：秒
	 * @param time
	 * @return
	 */
	public static String dateFomart(long time){
		SimpleDateFormat sf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date date=new Date(time);
		return sf.format(date);
	}
	public static String dateFomartyx(long time){
		SimpleDateFormat sf=new SimpleDateFormat("yyyy-MM-dd");
		Date date=new Date(time);
		return sf.format(date);
	}
	/**
	 * 12.13dzq 时间戳转化，默认年-月-日 时：分：秒
	 * @param time 时间戳
	 * @param fomart 转化格式
	 * @return
	 */
	public static String fomart(long time,String fomart){
		SimpleDateFormat sf= new SimpleDateFormat(fomart==null?"yyyy-MM-dd HH:mm:ss":fomart);
		Date date=new Date(time);
		return sf.format(date);
	}
	
    public static String dateStr(Long date,String f) {
        if(date==null){
            return null;
        }
        SimpleDateFormat format = new SimpleDateFormat(f);
        String str = format.format(getDate(date));
        return str;
    }
    
    public static long getDateLong(String datestr,String f) throws ParseException {
        
        SimpleDateFormat sdf = new SimpleDateFormat(f);
        Date date;
        
        date = sdf.parse(datestr);
        return DateUtils.getTimeLong(date);
    }
    
    /**
	 * 四舍五入
	 * @param num
	 * @return
	 */
    public static String dateToStayTWO(Double num){
    	
		DecimalFormat df4 = new DecimalFormat("##.##"); 

		return num==0d?"0":df4.format(num);
	}
	/**
	 * 将秒转换成时间
	 * @param times
	 * @return
	 */
	public static Date getDate(long times) {
		return new Date(times*1000);
	}
	
	/**
	 * 根据传递的String 比如 :2016-12-11 07:10 转成时间日期对象
	 * 
	 * @auth liaozhanggen 2016-12-13 下午4:13:21
	 */
	public static Date getFomartToDate(String time,String regx) throws ParseException {
		SimpleDateFormat formatter=new SimpleDateFormat(regx);
		Date date=formatter.parse(time);
		return date;
	}
	/** 
	 * @Description：判断是否符合 ****年（**月或*月）只能是2000到2099年
	 * @Author：yuxin
	 * @Create Date：2017-03-22
	 * @param：
	 * @return：
	 */
	public static boolean isyearmonth(String str) {
		Pattern regex = Pattern.compile("^[2][0][0-9]{2}年(0[0-9]|1[0-2]|[0-9])月");
		Matcher matcher = regex.matcher(str);
		boolean isMatched = matcher.matches();
		return isMatched;
	}
	/** 
	 * @Description：判断是否日期符合 ****-（**或*）只能是2000-2099  如2017-03 支持2017-3 2017-0 2017-00
	 * @Author：yuxin
	 * @Create Date：2017-03-23
	 * @param：
	 * @return：
	 */
	public static boolean isDate(String str) {
		Pattern regex = Pattern.compile("^[2][0][0-9]{2}-(0[0-9]|1[0-2]|[0-9])");
		Matcher matcher = regex.matcher(str);
		boolean isMatched = matcher.matches();
		return isMatched;
	}
	
	/**
	 * 根据传递的日期字符串格式，判断其他格式是否正确，并返回结果
	 * 
	 * @auth liaozhanggen 2016-12-13 下午4:13:21
	 */
	public static Date getFomartToDate(String dateStr) throws BusinessException {
		Date date = null;
		HashMap<String, String> dateRegFormat = new HashMap<String, String>();
		dateRegFormat.put("^\\d{4}\\D+\\d{1,2}\\D+\\d{1,2}\\D+\\d{1,2}\\D+\\d{1,2}\\D+\\d{1,2}\\D*$","yyyy-MM-dd-HH-mm-ss");// 2014年3月12日 13时5分34秒，2014-03-12
																															// 12:05:34，2014/3/12 12:5:34
		dateRegFormat.put("^\\d{4}\\D+\\d{2}\\D+\\d{2}\\D+\\d{2}\\D+\\d{2}$","yyyy-MM-dd-HH-mm");// 2014-03-12 12:05
		/***如果后面还有相应的格式要求 ，可以逐一释放 */
//		dateRegFormat.put("^\\d{4}\\D+\\d{2}\\D+\\d{2}\\D+\\d{2}$","yyyy-MM-dd-HH");// 2014-03-12 12
//		dateRegFormat.put("^\\d{4}\\D+\\d{2}\\D+\\d{2}$", "yyyy-MM-dd");// 2014-03-12
		dateRegFormat.put("^\\d{4}\\D+\\d{2}$", "yyyy-MM");// 2014-03
//		dateRegFormat.put("^\\d{4}$", "yyyy");// 2014
//		dateRegFormat.put("^\\d{14}$", "yyyyMMddHHmmss");// 20140312120534
//		dateRegFormat.put("^\\d{12}$", "yyyyMMddHHmm");// 201403121205
//		dateRegFormat.put("^\\d{10}$", "yyyyMMddHH");// 2014031212
//		dateRegFormat.put("^\\d{8}$", "yyyyMMdd");// 20140312
//		dateRegFormat.put("^\\d{6}$", "yyyyMM");// 201403
//		dateRegFormat.put("^\\d{2}\\s*:\\s*\\d{2}\\s*:\\s*\\d{2}$","yyyy-MM-dd-HH-mm-ss");// 13:05:34  拼接当前日期
//		dateRegFormat.put("^\\d{2}\\s*:\\s*\\d{2}$", "yyyy-MM-dd-HH-mm");// 13:05 
//																			// 拼接当前日期
//		dateRegFormat.put("^\\d{2}\\D+\\d{1,2}\\D+\\d{1,2}$", "yy-MM-dd");// 14.10.18(年.月.日)
//		dateRegFormat.put("^\\d{1,2}\\D+\\d{1,2}$", "yyyy-dd-MM");// 30.12(日.月)
//																	// 拼接当前年份
//		dateRegFormat.put("^\\d{1,2}\\D+\\d{1,2}\\D+\\d{4}$", "dd-MM-yyyy");// 12.21.2013(日.月.年)

		DateFormat formatter2;
		String dateReplace;
		try {
			for (String key : dateRegFormat.keySet()) {
				if (Pattern.compile(key).matcher(dateStr).matches()) {
					formatter2 = new SimpleDateFormat(dateRegFormat.get(key));
					dateReplace = dateStr.replaceAll("\\D+", "-");
					date = formatter2.parse(dateReplace);
					break;
				}
			}
			if (null == date) {
				Integer.valueOf("abc");
			}
		} catch (Exception e) {
			throw new BusinessException(ResultCode.SERVERERROR_NOEXECUTION,"日期格式无效");
		} 
		return date;
	}

	public static long getTime(Date date) {
		return date.getTime() / 1000;
	}

	public static int getDay(Date d){
		Calendar cal=Calendar.getInstance();
		cal.setTime(d);
		return cal.get(Calendar.DAY_OF_MONTH);
	}
	
	/**
	 * s - 表示 "yyyy-mm-dd" 形式的日期的 String 对象 
	 * @param
	 * @return
	 */
	public static Date valueOf(String s){
		final int YEAR_LENGTH = 4;
        final int MONTH_LENGTH = 2;
        final int DAY_LENGTH = 2;
        final int MAX_MONTH = 12;
        final int MAX_DAY = 31;
        int firstDash;
        int secondDash;
        Date d = null;

        if (s == null) {
            throw new IllegalArgumentException();
        }

        firstDash = s.indexOf('-');
        secondDash = s.indexOf('-', firstDash + 1);
        if ((firstDash > 0) && (secondDash > 0) && (secondDash < s.length()-1)) {
            String yyyy = s.substring(0, firstDash);
            String mm = s.substring(firstDash + 1, secondDash);
            String dd = s.substring(secondDash + 1);
            if (yyyy.length() == YEAR_LENGTH && mm.length() == MONTH_LENGTH &&
                dd.length() == DAY_LENGTH) {
                int year = Integer.parseInt(yyyy);
                int month = Integer.parseInt(mm);
                int day = Integer.parseInt(dd);
                if (month >= 1 && month <= MAX_MONTH) {
                    int maxDays = MAX_DAY;
                    switch (month) {
                        // February determine if a leap year or not
                        case 2:
                            if((year % 4 == 0 && !(year % 100 == 0)) || (year % 400 == 0)) {
                                maxDays = MAX_DAY-2; // leap year so 29 days in February
                            } else {
                                maxDays = MAX_DAY-3; //  not a leap year so 28 days in February 
                            }
                            break;
                        // April, June, Sept, Nov 30 day months
                        case 4:
                        case 6:
                        case 9:
                        case 11:
                            maxDays = MAX_DAY-1;
                            break;
                    }
                    if (day >= 1 && day <= maxDays) {
                        Calendar cal=Calendar.getInstance();
                        cal.set(year, month - 1, day,0,0,0);
                        cal.set(Calendar.MILLISECOND, 0);
                        d=cal.getTime();
                    }
                }
            }
        }
        if (d == null) {
            throw new IllegalArgumentException();
        }
        return d;
	}
	
	
	public static Date rollDay(Date d,int day){
		Calendar cal=Calendar.getInstance();
		cal.setTime(d);
		cal.add(Calendar.DAY_OF_MONTH, day);
		return cal.getTime();
	}
	public static Date rollMon(Date d,int mon){
		Calendar cal=Calendar.getInstance();
		cal.setTime(d);
		cal.add(Calendar.MONTH, mon);
		return cal.getTime();
	}
	public static Date rollYear(Date d,int year){
		Calendar cal=Calendar.getInstance();
		cal.setTime(d);
		cal.add(Calendar.YEAR, year);
		return cal.getTime();
	}
	public static Date rollDate(Date d,int year,int mon,int day){
		Calendar cal=Calendar.getInstance();
		cal.setTime(d);
		cal.add(Calendar.YEAR, year);
		cal.add(Calendar.MONTH, mon);
		cal.add(Calendar.DAY_OF_MONTH, day);
		return cal.getTime();
	}
	public static Date getDayFirstTime(Date d){
		Calendar cal = Calendar.getInstance();
		cal.setTimeInMillis(d.getTime());
		cal.set(Calendar.HOUR_OF_DAY, 0);
		cal.set(Calendar.SECOND, 0);
		cal.set(Calendar.MINUTE, 0);
		cal.set(Calendar.MILLISECOND, 0);
		return cal.getTime();
	}
	
	/**
	 * 获取当前时间的秒数字符串
	 * @return
	 */
	public static Long getNowTimeStr(){
		return System.currentTimeMillis() / 1000;
	}
	
	/**
	 * 获取当前时间的毫秒数字符串
	 * @return
	 */
	public static Long getNowTime(){
		return System.currentTimeMillis();
	}
	
	/**
	 * 设置过期时间
	 * @return
	 */
	public static Long setExpiredTime(Long nowTime, Integer expiredType, Integer expiredTime) {
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(new Date(nowTime*1000));
		calendar.add(expiredType, expiredTime);
		Long codeExpiredTime = getTimeLong(calendar.getTime());
		return codeExpiredTime;
	}
	
	/**
	 * 判断时间1是否大于时间2
	 * @param time1
	 * @param time2
	 * @return
	 */
	public static boolean compareTime(Long time1,Long time2) {
		boolean flag = true;
		if(time1 <= time2) {
			flag = false;
		}
		return flag;
	}
	
	public static String getTimeStr(Date time){
		long date = time.getTime();
		String str=Long.toString(date / 1000);
		return str;
	}
	
    public static long getTimeLong(Date time){
        long date = time.getTime();
        long longdate=date / 1000;
        return longdate;
    }
	
	
	public static long rollMonth(long addtime,int time_limit){
		Date t=DateUtils.rollDate(DateUtils.getDate(addtime), 0, time_limit,0);
		return t.getTime()/1000;
	}
	
	public static long rollDay(long addtime,int time_limit_day){
		Date t=DateUtils.rollDate(DateUtils.getDate(addtime), 0, 0,time_limit_day);
		return t.getTime()/1000;
	}
	
	/**
	 * 当月第一天
	 * @return
	 */
	public static Date getMonthFirstTime(){
		Calendar cal = Calendar.getInstance();
		cal.set(Calendar.DAY_OF_MONTH, 1);
		cal.set(Calendar.HOUR_OF_DAY, 0);
		cal.set(Calendar.SECOND, 0);
		cal.set(Calendar.MINUTE, 0);
		cal.set(Calendar.MILLISECOND, 0);
		return cal.getTime();
	}
	
	/**
	 * 当月最后一天
	 * @return
	 */
	public static Date getMonthLastTime(){
		Calendar cal = Calendar.getInstance();
		cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DAY_OF_MONTH));
		cal.set(Calendar.HOUR_OF_DAY, 23);
		cal.set(Calendar.SECOND, 59);
		cal.set(Calendar.MINUTE, 59);
		cal.set(Calendar.MILLISECOND, 0);
		return cal.getTime();
	}
	
	public static Date getIntegralTime(){
		Calendar cal = Calendar.getInstance();
		cal.set(Calendar.HOUR_OF_DAY, 0);
		cal.set(Calendar.SECOND, 0);
		cal.set(Calendar.MINUTE, 0);
		cal.set(Calendar.MILLISECOND, 0);
		return cal.getTime();
	}
	
	public static Date getLastIntegralTime(){
		Calendar cal = Calendar.getInstance();
		cal.set(Calendar.HOUR_OF_DAY, 23);
		cal.set(Calendar.SECOND, 59);
		cal.set(Calendar.MINUTE, 59);
		cal.set(Calendar.MILLISECOND, 0);
		return cal.getTime();
	}
	
	public static Date getLastSecIntegralTime(Date d){
		Calendar cal = Calendar.getInstance();
		cal.setTimeInMillis(d.getTime());
		cal.set(Calendar.HOUR_OF_DAY, 23);
		cal.set(Calendar.SECOND, 59);
		cal.set(Calendar.MINUTE, 59);
		cal.set(Calendar.MILLISECOND, 0);
		return cal.getTime();
	}
	
	public static long getTime(String format){
		long t=0;
		if(StringUtils.isBlank(format)) return t;
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date date;
		try {
			date = sdf.parse(format);
			t=date.getTime()/1000;
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return t;
	}
	
	/**
	 * 从第二天开始算起 如计算5月1日到10月1日，计算从5月2日开始到10月1日的天数
	 * @Title: daysBetween 
	 * @Description: TODO
	 * @param @param smdate
	 * @param @param bdate
	 * @param @return
	 * @param @throws ParseException 设定文件 
	 * @return int 返回类型 
	 * @throws
	 */
    public static int daysBetween(String smdate,String bdate) throws ParseException{  
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");  
        Calendar cal = Calendar.getInstance();    
        cal.setTime(sdf.parse(smdate));    
        long time1 = cal.getTimeInMillis();                 
        cal.setTime(sdf.parse(bdate));    
        long time2 = cal.getTimeInMillis();         
        long between_days=(time2-time1)/(1000*3600*24);  
            
       return Integer.parseInt(String.valueOf(between_days));     
    } 
    
    /**
     * 
     * @Title: dateadd 
     * @Description: TODO
     * @param @param datetime
     * @param @param days
     * @param @return 设定文件 
     * @return long 返回类型 
     * @throws
     */
    public static long dateadd(long datetime, int days){
        
        return (datetime+days*24*60*60);
    }
    
    public static String dateStr4(String times) {
		return dateStr4(getDate(times));
	}
    
    /**
	 * 将秒转换成时间
	 * @param times
	 * @return
	 */
	public static Date getDate(String times) {
		long time = Long.parseLong(times);
		return new Date(time*1000);
	}
    
    public static String dateStr4(Date date) {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String str = format.format(date);
		return str;
	}
    
	
//	public static void main(String[] args) throws ParseException {
//	    
//	    //System.out.print(DateUtils.getDateLong("04-23-2015", "MM-dd-yyyy"));
//	    
////		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
////		Date date;
////		try {
////			date = sdf.parse("2012-02-04");
////			System.out.println(DateUtils.getTimeStr(date));
////		} catch (ParseException e) {
////			// TODO Auto-generated catch block
////			e.printStackTrace();
////		}
//		System.out.println(getMonthFirstTime());
//		System.out.println(getMonthLastTime());
////	    System.out.println(getNowTimeStr());
////	    System.out.println(rollMonth(1431573013, 1));
////	    System.out.println(dateStr(rollMonth(1431573013,1), "yyyy年MM月dd日"));
////	    System.out.println(dateStr(setExpiredTime(getNowTimeStr(), Calendar.MINUTE, 20), "yyyy-MM-dd HH:mm:ss"));
////		int a=1360030690-1328284800;
////		System.out.println(DateUtils.getIntegralTime().getTime()/1000);
////		System.out.println(DateUtils.getLastIntegralTime().getTime()/1000);
////		int daytem = daysBetween(dateStr2("1411904015"), dateStr2(getNowTimeStr()));
////		Date date = new Date();
////		
////	    
////	    System.out.println(dateStr(1431587617L, "yyyyMMdd"));
//		
//	}
	/** 
	 * @Description：计算工作年限(单位为天比如返回20就是20天 500就是500天)
	 * @Author：yuxin
	 * @Create Date：2017/2/28/0028
	 * @param：
	 * @return：
	 */
	public static int getworkeryear(long ctime){
		long time=System.currentTimeMillis();
		int  workeryear=(int) ((time -ctime)/86400000);
		return workeryear;
	}
	/** 
	 * @Description：根据生日时间戳，计算年龄-周岁
	 * 
	 * @Author：juchengyang
	 *  update code liaozhanggen 2017-03-23 Long =>long
	 * @Create 2017-03-23
	 */
	public static int getAge(long birth) throws IllegalArgumentException {
        Calendar birthDay = Calendar.getInstance();
        birthDay.setTime(new Date(birth));
		//获取当前系统时间
		Calendar cal = Calendar.getInstance();
		//如果出生日期大于当前时间，则抛出异常
		if (cal.before(birthDay)) {
//			throw new RespException(ResultCode.FAILED, "生日日期大于当前时间"); update by liaozhanggen 20107-05-24 16:48 去除防止调用方整个个接口异常
			return 0;
		}
		//取出系统当前时间的年、月、日部分
		int yearNow = cal.get(Calendar.YEAR);
		int monthNow = cal.get(Calendar.MONTH);
		int dayOfMonthNow = cal.get(Calendar.DAY_OF_MONTH);
		//取出出生日期的年、月、日部分
		int yearBirth = birthDay.get(Calendar.YEAR);
		int monthBirth = birthDay.get(Calendar.MONTH);
		int dayOfMonthBirth = birthDay.get(Calendar.DAY_OF_MONTH);
		//当前年份与出生年份相减，初步计算年龄
		int age = yearNow - yearBirth;
		//当前月份与出生日期的月份相比，如果月份小于出生月份，则年龄上减1，表示不满多少周岁
		if (monthNow <= monthBirth) {
		//如果月份相等，在比较日期，如果当前日，小于出生日，也减1，表示不满多少周岁
			if (monthNow == monthBirth) {
				if (dayOfMonthNow < dayOfMonthBirth){
					age--;
				}
			} else {
				age--;
			}
		}
		return age;
	}
	
}
